<?php
/**
 * Created by PhpStorm.
 * User: madong
 * Date: 2018/8/28
 * Time: 下午6:28
 */

namespace app\api\controller;

use think\Config;
use think\Controller;
use app\api\model\User as Usertable;
use think\Db;
use app\api\model\Adeth;
use app\api\model\Logtrue;
use think\Request;

class Coin extends Controller
{

    private $coin_host_ip = '47.92.195.55';

    private $gas_default = 0.0005;//单位ether

    private $zongdizhi = '0xD1A6e12B4C929193E6e17C81Ee9AfEb2e59618Dc';//兑换时用来接收扣除的ETH的钱包地址


    /*
     * 更新用户所有钱包余额
     *
     * 参数
     *
     * @uname  用户名
     *
     * @address  要查询的钱包地址
     *
     *
     */

    public function Get_user_info_data($uname = '', $address = '')

    {

        $coin_name_arr = ['eth', 'omec', 'ae', 'btm', 'snt', 'iost', 'zrx', 'zil'];

        for ($i = 0; $i < count($coin_name_arr); $i++) {

            if ($i == count($coin_name_arr)) {

                $this->Get_balance_no_log($uname, $coin_name_arr[$i], $address);

                echo json_encode(['status' => 1]);

            } else {

                $this->Get_balance_no_log($uname, $coin_name_arr[$i], $address);

            }

        }

    }

    /*
     * 获取去充值列表
     *
     * 参数
     *
     * @uname 当前用户名
     *
     * @coin_type 货币类型
     *
     * 返回
     *
     * 返回交易记录列表
     *
     */
    public function Get_coin_log($uname = '', $coin_type = '')
    {

        echo json_encode(Db::name('logtrue')->where('uname', $uname)->where('type', $coin_type)->order('id desc')->select());


    }

    /*
     * 转账操作
     *
     * 参数
     *
     * @uname  用户名
     *
     * @coin_type  货币类型
     *
     * @to 接收方地址
     *
     * @value  转账数量
     *
     * 返回
     *
     *当前交易哈希
     */

    public function zhuanzhang()

    {
        $res = Request::instance();

        $uname = $res->param('uname');

        $bizhong = strtolower($res->param('coin_type'));

        $to = $res->param('to');

        $value = $res->param('value');

        $pass = $res->param('pass');

        if ($res->isPost()) {

            if (md5($pass) == Db::name('user')->where('uname', $uname)->value('secpwd')) {

                $adr_key_data = [

                    'address' => Db::name('adeth')->where('uname', $res->param('uname'))->value('address'),

                    'key' => Db::name('adeth')->where('uname', $res->param('uname'))->value('key')

                ];
                $balance = json_decode(file_get_contents('http://coin.czuv.net:3000/getBalance?address='.$adr_key_data['address'].'&Contractaddress='.Config::get('con_' . $bizhong).'&type='.$bizhong))->balance;
                $eth_balance = json_decode(file_get_contents('http://coin.czuv.net:3000/getBalance?address='.$adr_key_data['address'].'&Contractaddress&type=eth'))->balance;
                // if (round($eth_balance,5)<=0.0005){echo json_encode(['zt'=>0,'msg'=>'手续费不足,确保ETH有0.0005个']);die();}

                //     if ($value > round($balance+0.0005,5)){echo json_encode(['zt'=>0,'msg'=>'转出数量不能超过账户总数量']);die();}
                if(floatval($eth_balance)<0.0005){
                    echo json_encode(['zt'=>0,'msg'=>'ETH账户不足0.005']);die();
                }
                if($bizhong == 'eth'){
                    if(floatval($balance)<floatval($value+0.005)){echo json_encode(['zt'=>0,'msg'=>'不能超过账户余额']);die();}
                }else{
                    if(floatval($balance)<floatval($value)){echo json_encode(['zt'=>0,'msg'=>'不能超过账户余额']);die();}
                }
                
                //die();

                    //开始执行接口转账操作
                    
                    $zhuanzhang = file_get_contents('http://coin.czuv.net:3000/sendTransaction?contract='.Config::get('con_' . $bizhong).'&from='.$adr_key_data['address'].'&key='.$adr_key_data['key'].'&to='.$to.'&value='.$value.'&type='.$bizhong.'&nonce&gas');

                    // $daibi_zhuan = file_get_contents('http://' . $this->coin_host_ip . ':8885/?type=2&from=' .
                    //     $adr_key_data['address'] . '&privateKey=' . $adr_key_data['key'] . '&to=' . $to . '&value=' . $value . '&contract=' . Config::get('con_' . $bizhong));

                    if (strlen(json_decode($zhuanzhang)->hash) < 60){

                        echo json_encode(['zt'=>0,'msg'=>'转出失败，请稍后重试!']);

                    }else{

                        echo json_encode(['zt'=>1,'msg'=>'广播成功']);

                    }
                //echo json_encode(['zt'=>0,'msg'=>$eth_balance]);

                //die();

                // if ($bizhong == 'eth') {//如果是ETH执行该处

                //     //转账前先获取ETH的真是余额

                //     $eth_balance = json_decode(file_get_contents('http://' . $this->coin_host_ip . ':8883/?type=4&account=' . $adr_key_data['address']), true)['Balance'] + $this->gas_default;

                //     if ($value > round($eth_balance,5)) {
                //         echo json_encode(['zt' => 0, 'msg' => '手续费不足']);
                //         die();
                //     }

                //     //执行ETH转账接口进行实际转账

                //     $zhuan = file_get_contents('http://' . $this->coin_host_ip . ':8884/?type=3&from=' .
                //         $adr_key_data['address'] . '&privateKey=' . $adr_key_data['key'] . '&to=' . $to . '&value=' .
                //         $value);

                //     if (strlen(json_decode($zhuan)->hash) < 60){

                //         echo json_encode(['zt'=>0,'msg'=>'转出失败稍后重试!']);
                //     }else{

                //         echo json_encode(['zt' => 1, 'msg' =>'广播成功']);

                //     }


                // } else {//如果不是eth执行代币转账

                    // //先获取代币的真是余额
                    // $token_balance = json_decode(file_get_contents('http://' . $this->coin_host_ip . ':8882/?type=token_balance&con_addr=' . Config::get('con_' . $bizhong) . '&account=' . $adr_key_data['address']))->balance;

                    // //获取以太坊实际余额，保证发送代币的手手续费

                    // $eth_balance = json_decode(file_get_contents('http://' . $this->coin_host_ip . ':8883/?type=4&account=' . $adr_key_data['address']), true)['Balance'] + $this->gas_default;

                    // if (round($eth_balance,5)<=0.0005){echo json_encode(['zt'=>0,'msg'=>'手续费不足,确保ETH有0.0005个']);die();}

                    // if ($value > round($token_balance,5)){echo json_encode(['zt'=>0,'msg'=>'转出数量不能超过账户总数量']);die();}

                    // //开始执行接口转账操作

                    // $daibi_zhuan = file_get_contents('http://' . $this->coin_host_ip . ':8885/?type=2&from=' .
                    //     $adr_key_data['address'] . '&privateKey=' . $adr_key_data['key'] . '&to=' . $to . '&value=' . $value . '&contract=' . Config::get('con_' . $bizhong));

                    // if (strlen(json_decode($daibi_zhuan)->hash) < 60){

                    //     echo json_encode(['zt'=>0,'msg'=>'转出失败，请稍后重试!']);

                    // }else{

                    //     echo json_encode(['zt'=>1,'msg'=>'广播成功']);

                    // }



                // }

            } else {

                echo json_encode(['zt' => 0, 'msg' => '支付密码错误!']);

            }

        } else {


        }


    }

    //获取当前用户私钥

    public function Get_user_key()
    {

        $Aeth_obj = new Adeth();

        $res = Request::instance();

        $uname = $this->Jiemi($res->param('uname'));
        // echo json_encode(['zt'=>1,'msg'=>'jhkjhjhk']);die();

        if ($res->isPost()) {

            $data = $Aeth_obj->Get_user_key($uname);

            if ($data) {

                echo json_encode(['zt' => 1, 'msg' => '私钥获取成功', 'data' => $this->Jiami($data)]);

            } else {

                echo json_encode(['zt' => 0, 'msg' => '私钥获取失败']);

            }

        } else {

            echo json_encode(['zt' => 2, 'msg' => 'error']);

        }

    }

    //获取当前用户私钥备份状态
    public function Get_user_key_status($uname)
    {

        $aeth_obj = new Adeth();

        $res = Request::instance();

        if ($res->isPost()) {

            echo json_encode(['msg' => $aeth_obj->Get_key_backup_status($uname)]);

        } else {

            return 'error';

        }

    }

    //修改备份状态
    public function update_kye_status()
    {

        $res = Request::instance();

        if ($res->isPost()) {

            if (Db::name('adeth')->where('uname', $res->param('uname'))->update(['tanchuang' => 1])) {

                return 1;//状态修改成功

            } else {

                return 0;//状态修改失败

            }

        } else {

            return '错误请求';

        }

    }

    //根据账号查询当前账户的实际余额(接口查询)

    public function Get_Balance()
    {
        //echo json_encode(['zt'=>1,'msg'=>'余额更新成功','data'=>111]);die();

        $res = Request::instance();

        $uname = $res->param('uname');

        $coin_type = strtolower($res->param('bizhong'));

        $coin_user_obj = new Adeth();

        $user_address = $coin_user_obj->where('uname', $uname)->value('address');


        $user_yuer = $coin_user_obj->where('uname', $uname)->value($coin_type);
        //dump($user_yuer);die();

        $balance = json_decode(file_get_contents('http://coin.czuv.net:3000/getBalance?address='.$user_address.'&Contractaddress='.Config::get('con_' . $coin_type).'&type='.$coin_type))->balance;

        if ($balance || $balance == 0) {

            if (((int)($user_yuer * 10000)) / 10000 == ((int)($balance * 10000)) / 10000) {

                echo json_encode(['zt' => 1, 'msg' => '余额更新成功', 'data' => $balance]);

            } else {

                if (Db::name('adeth')->where('uname', $uname)->update([$coin_type => $balance])) {

                    echo json_encode(['zt' => 1, 'msg' => '余额更新成功', 'data' => $balance]);

                } else {

                    echo json_encode(['zt' => 0, 'msg' => '余额获取失败']);

                }

            }

        } else {

            echo json_encode(['zt' => 0, 'msg' => '余额获取失败']);

        }

//        if ($coin_type == 'eth') {
//
//            $balance = json_decode(file_get_contents('http://' . $this->coin_host_ip . ':8883/?type=4&account=' . $user_address))->Balance;
//
//            if ($balance || $balance == 0) {
//
//                if (((int)($user_yuer * 10000)) / 10000 == ((int)($balance * 10000)) / 10000) {
//
//                    echo json_encode(['zt' => 1, 'msg' => '余额更新成功', 'data' => $balance]);
//
//                } else {
//
//                    if (Db::name('adeth')->where('uname', $uname)->update([$coin_type => $balance])) {
//
//                        echo json_encode(['zt' => 1, 'msg' => '余额更新成功', 'data' => $balance]);
//
//                    } else {
//
//                        echo json_encode(['zt' => 0, 'msg' => '余额获取失败']);
//
//                    }
//
//                }
//
//            } else {
//
//                echo json_encode(['zt' => 0, 'msg' => '余额获取失败']);
//
//            }
//
//        } else {
//
//            $balance = json_decode(file_get_contents('http://' . $this->coin_host_ip . ':8882/?type=token_balance&con_addr=' . Config::get('con_' . $coin_type) . '&account=' . $user_address))->balance;
//
//            if (((int)($user_yuer * 10000)) / 10000 == ((int)($balance * 10000)) / 10000) {
//
//                echo json_encode(['zt' => 1, 'msg' => '余额更新成功', 'data' => $balance]);
//
//            } else {
//
//                if ($balance || $balance == 0) {
//
//                    if (Db::name('adeth')->where('uname', $uname)->update([$coin_type => $balance])) {
//
//                        echo json_encode(['zt' => 1, 'msg' => '余额更新成功', 'data' => $balance]);
//
//                    } else {
//
//                        echo json_encode(['zt' => 0, 'msg' => '余额获取失败']);
//
//                    }
//
//                } else {
//
//                    echo json_encode(['zt' => 0, 'msg' => '余额获取失败']);
//
//                }
//
//            }
//
//        }


    }

    //获取数据库余额(单币种)-（1）
    public function Get_data_balance()
    {
        $res = Request::instance();

        $uname = $res->param('uname');

        $coin_type = $res->param('bizhong');

        $coin_user_obj = new Adeth();

        $data = $coin_user_obj->where('uname', $uname)->value($coin_type);

        if ($data) {

            echo json_encode(['zt' => 1, 'msg' => '获取成功', 'data' => $data]);

        } else {

            echo json_encode(['zt' => 0, 'msg' => '余额获取失败']);

        }

    }

    //获取ETH单条汇率(不能获取数据库的老数据要急时响应)
    public function Get_huilv()
    {
        $huilv = Db::name('hangqing')->where('id',1)->value('huilv');

        //$eth = json_decode(file_get_contents('https://api.coinmarketcap.com/v2/ticker/1027/'), true)
        //['data']['quotes']['USD']['price'];

        $eth = Db::name('hangqing')->where('id',1)->value('eth');

        if ($eth) {

            echo json_encode(['zt' => 1, 'msg' => round(floatval($eth) * floatval($huilv), 2)]);

        } else {

            echo json_encode(['zt' => 0, 'msg' => '当前价格获取失败']);

        }


    }

    //获取所有的余额(1)
    public function Get_all_yuer()
    {

        $res = Request::instance();

        $uname = $res->param('uname');

        $aethobj = new Adeth();

        $data = $aethobj->where('uname', $uname)->column('uname,eth,omec,ae,btm,snt,iost,zrx,zil,gusd')[$uname];

        if ($res) {

            echo json_encode(['zt' => 1, 'msg' => '余额获取成功', 'data' => $data]);

        } else {

            echo json_encode(['zt' => 0, 'msg' => '获取失败', 'data' => 0]);

        }

    }

    //验证用户支付密码
    public function ifvpaypwd()
    {

        $post_data = Request::instance();

        if ($post_data->isPost()) {

            $pay_pwd = Db::name('user')->where('uname', $post_data->param('uname'))->value('secpwd');

            if (md5($post_data->param('pwd')) == $pay_pwd) {

                echo json_encode(['zt' => 1, 'msg' => '支付密码正确']);

            } else {

                echo json_encode(['zt' => 0, 'msg' => '支付密码错误']);

            }

        } else {

            echo json_encode(['zt' => 0, 'msg' => 'methos error']);

        }

    }

    //数据解密
    private function Jiemi($data)
    {

        $jiami_data = openssl_decrypt(base64_decode($data, false), "AES-128-CBC", Config::get('Key'), OPENSSL_RAW_DATA, Config::get('IV'));

        return $jiami_data;

    }

    //数据加密
    private function Jiami($data)
    {

        $jiemi_data = base64_encode(openssl_encrypt($data, "AES-128-CBC", Config::get('Key'), OPENSSL_RAW_DATA, Config::get('IV')));

        return $jiemi_data;

    }
}